package com.wontube.smr.web.controller.i18n;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.modle.vo.PagenateInfo;
import com.wontube.client.remote.Remoting;
import com.wontube.smr.client.model.po.Movie;
import com.wontube.smr.client.model.vo.AudioFiles;
import com.wontube.smr.client.model.vo.MVChartItems;
import com.wontube.smr.client.model.vo.MovieItems;
import com.wontube.smr.web.client.IMVWebHandler;
import com.wontube.smr.web.client.IMp3WebHandler;
import com.wontube.smr.web.client.model.bo.QueryItemParams;

@Controller
@RequestMapping("/world/music")
public class I18nMusicController {
	// 音乐排行榜参数
	private final static int CHART_PAGE_SIZE = 20;
	// 音乐明细参数
	private final static int BROWSE_PAGE_SIZE = 30;
	private final static int MP3_PAGE_SIZE = 50;
	
	@RequestMapping("")
	public void f3(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/world/music/");		
	}

	/**
	 * video music 首页
	 * 
	 * @return
	 */
	@RequestMapping("/")
	public ModelAndView musicHome() {
		return browseMusicHome();
	}
	
	@RequestMapping("/video")
	public void f4(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/world/music/video/");		
	}

	@RequestMapping("/video/")
	public ModelAndView browseMusicHome() {
		IMVWebHandler handler = getMVHandler();
		QueryItemParams params = new QueryItemParams();
		params.setNeedGenres(true);
		MovieItems items = handler.listYoutubeMusics(params, new PagenateInfo(1, BROWSE_PAGE_SIZE));
		ModelAndView mv = new ModelAndView("/i18n/music/music_index");
		mv.addObject("musicItems", items);
		if (items != null) {
			mv.addObject("genres", items.getGenres());
		}
		return mv;
	}

	@RequestMapping("/videos")
	public ModelAndView browses() {
		IMVWebHandler handler = getMVHandler();
		ModelAndView mv = new ModelAndView("/i18n/music/music_index");
		mv.addObject("genres", handler.getI18nMusicGenres());
		return mv;
	}

	@RequestMapping("/video/query")
	public ModelAndView music_query(QueryItemParams params,
			@RequestParam(value = "page", required = false, defaultValue = "1") Integer page) {
		IMVWebHandler handler = getMVHandler();
		params.setNeedGenres(false);
		MovieItems items = handler.listYoutubeMusics(params, new PagenateInfo(page, BROWSE_PAGE_SIZE));
		ModelAndView mv = new ModelAndView("/i18n/music/music_list");
		mv.addObject("musicItems", items);
		return mv;
	}

	@RequestMapping("/video/{id}")
	public ModelAndView browse_music_detail(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMVHandler();
		Movie movie = handler.getYoutubeMV(movieId);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("i18n/music/detail/detail_index");
			mv.addObject("show", movie);
			mv.addObject("genres", handler.getI18nMusicGenres());
			return mv;
		}
	}

	@RequestMapping("/video/watch-{id}")
	public ModelAndView browse_music_play(@PathVariable("id") String movieId, HttpServletResponse response)
			throws IOException {
		IMVWebHandler handler = getMVHandler();
		Movie movie = handler.getYoutubeMV(movieId);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("/i18n/music/play/music_player");
			mv.addObject("movie", movie);
			mv.addObject("genres", handler.getI18nMusicGenres());
			return mv;
		}
	}

	@RequestMapping("/video/relate/{id}")
	public ModelAndView moviesRelate(@PathVariable("id") String movieId) throws IOException {
		ModelAndView mv = new ModelAndView("/i18n/music/play/music_relate_video");
		IMVWebHandler handler = getMVHandler();
		QueryItemParams params = new QueryItemParams(false);
		MovieItems movieItems = handler.listYoutubeMusics(params, params.getPageInfo(6));
		List<Movie> list = new ArrayList<Movie>();
		for (Movie movie : movieItems.getItems()) {
			if (!movie.getId().equals(movieId) && list.size() < 5) {
				list.add(movie);
			}
		}
		mv.addObject("movieItems", list);
		return mv;
	}

	@RequestMapping("/video/alpha/{alpha}")
	public ModelAndView browseMusicsByAlpha(@PathVariable("alpha") String initial) throws IOException {
		return getMusicViewWithGenres(null, initial, null);
	}	

	@RequestMapping("/video/genre/{genre}")
	public ModelAndView browse_music_genre(@PathVariable("genre") String genre) throws IOException {
		return getMusicViewWithGenres(genre, null, null);
	}

	private ModelAndView getMusicViewWithGenres(String genre, String initial, Integer page) {
		if (page == null || page.intValue() < 1) {
			page = 1;
		}

		QueryItemParams params = new QueryItemParams();
		params.setNeedGenres(true);
		params.setGenre(genre);
		params.setInitial(initial);	

		IMVWebHandler handler = getMVHandler();
		MovieItems items = handler.listYoutubeMusics(params, new PagenateInfo(page, BROWSE_PAGE_SIZE));

		ModelAndView mv = new ModelAndView("i18n/music/music_index");
		mv.addObject("musicItems", items);
		if (items != null) {
			mv.addObject("genres", items.getGenres());
		}
		return mv;
	}
	
	@RequestMapping("/chart")
	public void f5(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/world/music/chart/");		
	}

	@RequestMapping("/chart/")
	public ModelAndView musicChart() {
		ModelAndView mv = new ModelAndView("/i18n/music/charts/charts_index");
		IMVWebHandler handler = getMVHandler();
		Map<String, MVChartItems> maps = handler.getYoutubeChartsHome();
		mv.addAllObjects(maps);	
		mv.addObject("hasMore", true);

		return mv;
	}

	@RequestMapping("/chart/query")
	public ModelAndView musicChartQuery(@RequestParam("period") String period,
			@RequestParam(value="page") Integer page, HttpServletResponse response) throws IOException {
		if(page == null || page < 1){
			page = 1;
		}
		
		IMVWebHandler handler = getMVHandler();
		PagenateInfo pageInfo = new PagenateInfo(page, CHART_PAGE_SIZE);		
		if("weekly".equals(period)){
			ModelAndView mv = new ModelAndView("/i18n/music/charts/weekly_list");			
			MVChartItems chartItems = handler.getYoutubeWeeklyCharts(pageInfo);
			mv.addObject("youtubeWeeklyItems", chartItems);	
			return mv;
		}else if("daily".equals(period)){
			ModelAndView mv = new ModelAndView("/i18n/music/charts/daily_list");			
			MVChartItems chartItems = handler.getYoutubeDailyCharts(pageInfo);
			mv.addObject("youtubeDailyItems", chartItems);	
			return mv;
		}	
			
		response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		return null;
	}
	
	@RequestMapping("/mp3")
	public void f6(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/world/music/mp3/");		
	}

	@RequestMapping("/mp3/")
	public ModelAndView music_mp3() {
		ModelAndView mv = new ModelAndView("/i18n/music/mp3/mp3_index");		
		IMVWebHandler handler = getMVHandler();		
		//vevoMusics && vevoArtists
		Map<String, Object> maps = handler.getMp3Home();
		mv.addAllObjects(maps);
		return mv;
	}
	
	@RequestMapping("/list/{page}")
	public ModelAndView listMusics(@RequestParam(value="ajax", required=false) String ajax,
			@PathVariable("page") Integer page) {
		if(page.intValue() < 1){
			page = 1;
		}
		
		ModelAndView mv = new ModelAndView();
		IMVWebHandler handler = getMVHandler();		
		MovieItems musicItems = handler.listVevoMusics(new PagenateInfo(page, MP3_PAGE_SIZE));		
		mv.addObject("vevoMusics", musicItems);
		
		if(ajax != null){		
			mv.setViewName("/i18n/music/mp3/mp3_list");	
		}else{
			mv.setViewName("/i18n/music/mp3/mp3_index");		
			mv.addObject("page", page);
			mv.addObject("vevoArtists", handler.listVevoTopArtists(new PagenateInfo(1, 25)));
		}
		
		return mv;		
	}
	
	@RequestMapping("/{query}")
	public ModelAndView searchMusic(@PathVariable("query") String query){
		return searchMusic(query, 1);
	}
	
	@RequestMapping("/{query}/{page}")
	public ModelAndView searchMusic(@PathVariable("query") String query, @PathVariable("page") Integer page){
		ModelAndView mv = new ModelAndView("/i18n/music/mp3/search_index");
		Remoting<IMp3WebHandler> remoting = new Remoting<IMp3WebHandler>();
		remoting.setReadTimeout(60000); // 查询较慢
		IMp3WebHandler handler = remoting.createService(IMp3WebHandler.class);
		AudioFiles files = handler.search(query, page);
		mv.addObject("audioFiles", files);
		mv.addObject("page", page);
		
		return mv;
	}
	
	@RequestMapping("/search")
	public ModelAndView searchMp3(@RequestParam("query") String query, 
			@RequestParam(value="page", required=false, defaultValue="1") Integer page){
		ModelAndView mv = new ModelAndView("i18n/music/mp3/mp3_search_result");
		Remoting<IMp3WebHandler> remoting = new Remoting<IMp3WebHandler>();
		remoting.setReadTimeout(60000); // 查询较慢
		IMp3WebHandler handler = remoting.createService(IMp3WebHandler.class);
		AudioFiles files = handler.search(query, page);
		mv.addObject("audioFiles", files);
		mv.addObject("query", query);
		mv.addObject("page", page);
		return mv;
	}
	
	private IMVWebHandler getMVHandler() {
		Remoting<IMVWebHandler> remoting = new Remoting<IMVWebHandler>();
		return remoting.createService(IMVWebHandler.class);
	}
}
